// var http = require("http")
// var bodyParser = require('body-parser')

// http.createServer(function (request, response) {
//     // 发送 HTTP 头部 
//     // HTTP 状态值: 200 : OK
//     // 内容类型: text/plain  application/json
//     response.writeHead(200, {'Content-Type': 'application/json'})
//     request.read
//     response.end(JSON.stringify({"name":"杰克"}))
// }).listen(9000)


const express = require('express')
// 参考 https://www.cnblogs.com/gxp69/p/7235911.html
// 参考 https://blog.csdn.net/yanyang1116/article/details/54847560
const bodyParser = require('body-parser')

var app = express()
app.listen(9000)

// 打开跨域配置
app.all('/test1', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

app.all('/test2', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});


// 全局设置
app.use(bodyParser.urlencoded({
    extended: false,                 //扩展模式
    limit:    2*1024*1024           //限制-2M
}))
// app.use(bodyParser.json())

// 创建 application/json 解析
var jsonParser = bodyParser.json()
// 创建 application/x-www-form-urlencoded 解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// 登录
app.post('/test1', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400)
    console.log(req.body.name, req.headers)
    res.send(JSON.stringify({"msg":req.body.name + "登录成功"}))
})


// 登录
app.post('/test2', urlencodedParser, function (req, res) {
    
    if (!req.body) return res.sendStatus(400)
    console.log(req.body.name, req.headers)
    res.send(JSON.stringify({"msg":req.body.name + "登录成功"}))
})


// app.use('/', function (req, res){
//     console.log(req) // POST
//      //req.query   GET
// 　  //req.body    POST
// })




// 获取ip地址
function getIPAdress(){
    var interfaces = require('os').networkInterfaces()
    for(var devName in interfaces){
        var iface = interfaces[devName]
        for(var i=0; i<iface.length; i++){
            var alias = iface[i]
            if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
                return alias.address
            }
        }
    }
}

// 打印服务器连接
console.log("Server running at http://" + getIPAdress() + ":9000")
